package com.iasku.iaskueleclass_phone.activity;

import java.util.ArrayList;
import java.util.Set;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.iasku.constant.Constant;
import com.iasku.iaskueleclass_phone.R;
import com.iasku.iaskueleclass_phone.ReturnData;
import com.iasku.iaskueleclass_phone.Status;
import com.iasku.manager.DataManager;
import com.iasku.manager.IDataManager;
import com.iasku.util.BaseUtil;

public class UserLoginActivity extends BaseActivity {
    private static final int TASK_USER_LOGIN = 1;
    private static final int TASK_GET_SCHOOLINFO = 2;
    private AutoCompleteTextView mUserNameEt;
    private EditText mPasswordEt,mSchoolIdEt;
    private SharedPreferences mPref;
    private ImageView mLoginIv;
    private String username,password,schoolid;
    private CheckBox mLoginCb;
    private Editor mEditor;
    private String mLoginData;
    private String mSchoolInfoData;
    
    private void initView(){
        try {
            VideoPlayActivity.class.newInstance();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mPref = PreferenceManager.getDefaultSharedPreferences(this);
        mEditor = mPref.edit();
        boolean isLog = mPref .getBoolean(Constant.EDIT_USERISLOG, false);
        if (isLog) {
            username = mPref .getString(Constant.USER_LOGIN_NAME, "");
            schoolid = mPref .getString(username+"_sid", "");
            Constant.USER_SHCOOL_ID = schoolid;
            String userinfo = mPref .getString(Constant.EDIT_USERINFO, "");
            Intent intent = new Intent();
            intent.setClass(this, MainActivity.class);
            intent.putExtra(Constant.USER_LOGIN_INFO, userinfo);
            intent.putExtra(Constant.SCHOOL_INFO,mPref.getString(Constant.SCHOOL_INFO, ""));
            startActivity(intent);
            finish();
        } else {
            mEditor = mPref.edit();
            setupView();
            addListener();
        }
    }
    
    private void setupView(){
        mUserNameEt= (AutoCompleteTextView) findViewById(R.id.et_username);
        mPasswordEt = (EditText) findViewById(R.id.et_password);
        mSchoolIdEt = (EditText) findViewById(R.id.et_schoolid);
        mLoginIv = (ImageView) findViewById(R.id.btn_user_login);
        mLoginCb = (CheckBox) findViewById(R.id.cb_savepass);
    }
    
    private void addListener() {
        mUserNameEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Set<String> set = mPref.getAll().keySet();
                String[] allUserName = new String[set.size()];
                int i = 0;
                for (String str : set) {
                    allUserName[i] = str;
                    i++;
                }
                ArrayList<String> names = new ArrayList<String>();
                for(int j=0;j<allUserName.length;j++){
                    if(!allUserName[j].endsWith("sid")){
                        names.add(allUserName[j]);
                    }
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(UserLoginActivity.this,
                        android.R.layout.test_list_item, names);
                mUserNameEt.setAdapter(adapter);// 设置数据适配器
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                username = s.toString();
                String schoolid = mPref.getString(username+"_sid", "");
                if (!"".equals(schoolid)) {
                    mSchoolIdEt.setText(schoolid);
                }
                mPasswordEt.setText(mPref.getString(mUserNameEt.getText().toString(), ""));
            }
        });

        // 用户登录
        mLoginIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
        
        mLoginCb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    buttonView.setButtonDrawable(R.drawable.login_check_box_yes);
                } else {
                    buttonView.setButtonDrawable(R.drawable.login_check_box_none);
                }
            }
        });
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_login_layout);
        initProgressDialog();
        initView();
    }
    
    private void login(){
        username = mUserNameEt.getText().toString().trim();
        password = mPasswordEt.getText().toString().trim();
        schoolid = mSchoolIdEt.getText().toString().trim();
        if ("".equals(username) || BaseUtil.isEmptyEt(mPasswordEt) || BaseUtil.isEmptyEt(mSchoolIdEt)) {
            BaseUtil.showText(this, "输入内容不能为空");
            return;
        }
        startTask(TASK_USER_LOGIN);
    }
    
    @Override
    public int onTaskComplete(int taskId, Status status) {
        mProgressDialog.dismiss();
        switch (taskId) {
        case TASK_USER_LOGIN:{
            switch (status.code) {
            case 2:
                loginSuccess(status);
                break;
            case -1:
            case 0:
            case 1:
                BaseUtil.showText(this, status.msg);
                break;
            }
        }
        break;
        case TASK_GET_SCHOOLINFO:{
            switch (status.code) {
            case 1:
                getSchoolInfoSuccess();
                break;
            case -1:
                BaseUtil.showText(this, status.msg);
                break;
            }
        }
        break;
        }
        return super.onTaskComplete(taskId, status);
    }
    
    //成功获取学校信息
    private void getSchoolInfoSuccess(){
        if (mLoginCb.isChecked()) {// 登陆成功才保存密码
            mEditor.putString(username, password);
            mEditor.putString(username+"_sid", schoolid);
            mEditor.putBoolean(Constant.EDIT_USERISLOG, true);
        } else {
            mEditor.remove(username);
            mEditor.remove(username+"_sid");
            mEditor.remove(Constant.EDIT_USERISLOG);
        }
        Constant.USER_SHCOOL_ID = schoolid;
        mProgressDialog.dismiss();
        Intent intent = new Intent();
        intent.setClass(this, MainActivity.class);
        mEditor.putString(Constant.SCHOOL_INFO,mSchoolInfoData);
        mEditor.commit();
        intent.putExtra(Constant.USER_LOGIN_INFO, mPref.getString(Constant.EDIT_USERINFO, ""));
        intent.putExtra(Constant.SCHOOL_INFO,mSchoolInfoData);
        finish();
        startActivity(intent);
    } 
    
    //登录成功
    private void loginSuccess(Status status) {
        String[] arr = mLoginData.split(":");
        mEditor.putString(Constant.USER_LOGIN_NAME ,username);
        if ("8".equals(arr[1]) || "10".equals(arr[1])) {
            BaseUtil.showText(this, status.msg);
            mEditor.putString(Constant.EDIT_USERINFO, mLoginData);
            mEditor.commit();
            startTask(TASK_GET_SCHOOLINFO);
        } else {
            mProgressDialog.dismiss();
            BaseUtil.showText(this, "不是学生，无法登录");
        }
    }

    @Override
    public int onTaskStart(int taskId, Bundle bundle) {
        if(taskId == TASK_USER_LOGIN){
            mProgressDialog.setMessage("正在登录...");
            mProgressDialog.show();
        }
        return super.onTaskStart(taskId, bundle);
    }
    
    @Override
    public Status onTaskInBackground(int taskId, Bundle bundle) {
        switch (taskId) {
        case TASK_USER_LOGIN:{
            IDataManager manager = DataManager.getInstance();
            ReturnData<String> mReturnData = manager.login(username, password, schoolid);
            mLoginData = mReturnData.getData();
            return new Status(mReturnData);
        }
        case TASK_GET_SCHOOLINFO:{
            IDataManager manager = DataManager.getInstance();
            ReturnData<String> mReturnData = manager.getSchoolInfo(schoolid);
            mSchoolInfoData = mReturnData.getData();
            return new Status(mReturnData);
        }
        }
        return super.onTaskInBackground(taskId, bundle);
    }
}
